﻿using System;
using StudentManagementSystem.DB;
using StudentManagementSystem.Repositories;
using StudentManagementSystem.Models;

namespace StudentManagementSystem
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("学生管理系统启动中...");

            // 初始化数据库上下文
            var dbContext = new DBContext("StudentManagement.db");

            // 初始化仓储
            var schoolRepository = new SchoolRepository(dbContext);
            var classRepository = new ClassRepository(dbContext);
            var studentRepository = new StudentRepository(dbContext);
            var logRepository = new LogRepository(dbContext);

            bool running = true;

            while (running)
            {
                Console.WriteLine("\n请选择操作：");
                Console.WriteLine("1. 学校管理");
                Console.WriteLine("2. 班级管理");
                Console.WriteLine("3. 学生管理");
                Console.WriteLine("4. 查看操作日志");
                Console.WriteLine("0. 退出系统");

                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        ManageSchools(schoolRepository, classRepository);
                        break;
                    case "2":
                        ManageClasses(schoolRepository, classRepository, studentRepository);
                        break;
                    case "3":
                        ManageStudents(classRepository, studentRepository);
                        break;
                    case "4":
                        ViewLogs(logRepository);
                        break;
                    case "0":
                        running = false;
                        Console.WriteLine("感谢使用学生管理系统，再见！");
                        break;
                    default:
                        Console.WriteLine("无效选择，请重新输入。");
                        break;
                }
            }
        }

        static void ManageSchools(SchoolRepository schoolRepository, ClassRepository classRepository)
        {
            bool running = true;

            while (running)
            {
                Console.WriteLine("\n学校管理：");
                Console.WriteLine("1. 添加学校");
                Console.WriteLine("2. 查看所有学校");
                Console.WriteLine("3. 查看学校详情");
                Console.WriteLine("4. 更新学校信息");
                Console.WriteLine("5. 删除学校");
                Console.WriteLine("0. 返回上一级");

                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        Console.WriteLine("请输入学校名称：");
                        string schoolName = Console.ReadLine();
                        Console.WriteLine("请输入学校地址：");
                        string schoolAddress = Console.ReadLine();

                        var newSchool = new School
                        {
                            Name = schoolName,
                            Address = schoolAddress
                        };

                        int schoolId = schoolRepository.Create(newSchool);
                        Console.WriteLine($"学校添加成功，ID：{schoolId}");
                        break;

                    case "2":
                        var schools = schoolRepository.GetAll();
                        Console.WriteLine("\n所有学校：");
                        Console.WriteLine("ID\t名称\t\t地址");
                        foreach (var school in schools)
                        {
                            Console.WriteLine($"{school.Id}\t{school.Name}\t\t{school.Address}");
                        }
                        break;

                    case "3":
                        Console.WriteLine("请输入学校ID：");
                        if (int.TryParse(Console.ReadLine(), out int viewSchoolId))
                        {
                            var school = schoolRepository.GetById(viewSchoolId);
                            if (school != null)
                            {
                                Console.WriteLine($"\n学校详情：ID={school.Id}, 名称={school.Name}, 地址={school.Address}, 创建时间={school.CreatedAt}");

                                var classes = classRepository.GetBySchoolId(viewSchoolId);
                                Console.WriteLine("\n该学校的班级：");
                                Console.WriteLine("ID\t名称");
                                foreach (var @class in classes)
                                {
                                    Console.WriteLine($"{@class.Id}\t{@class.Name}");
                                }
                            }
                            else
                            {
                                Console.WriteLine("未找到该学校！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "4":
                        Console.WriteLine("请输入要更新的学校ID：");
                        if (int.TryParse(Console.ReadLine(), out int updateSchoolId))
                        {
                            var schoolToUpdate = schoolRepository.GetById(updateSchoolId);
                            if (schoolToUpdate != null)
                            {
                                Console.WriteLine($"当前名称：{schoolToUpdate.Name}，请输入新名称（留空则保持不变）：");
                                string newName = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newName))
                                {
                                    schoolToUpdate.Name = newName;
                                }

                                Console.WriteLine($"当前地址：{schoolToUpdate.Address}，请输入新地址（留空则保持不变）：");
                                string newAddress = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newAddress))
                                {
                                    schoolToUpdate.Address = newAddress;
                                }

                                schoolRepository.Update(schoolToUpdate);
                                Console.WriteLine("学校信息更新成功！");
                            }
                            else
                            {
                                Console.WriteLine("未找到该学校！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "5":
                        Console.WriteLine("请输入要删除的学校ID：");
                        if (int.TryParse(Console.ReadLine(), out int deleteSchoolId))
                        {
                            // 确认删除
                            Console.WriteLine("警告：删除学校将同时删除其所有班级和学生！是否继续？(y/n)");
                            string confirm = Console.ReadLine();
                            if (confirm.ToLower() == "y")
                            {
                                schoolRepository.Delete(deleteSchoolId);
                                Console.WriteLine("学校删除成功！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "0":
                        running = false;
                        break;

                    default:
                        Console.WriteLine("无效选择，请重新输入。");
                        break;
                }
            }
        }

        static void ManageClasses(SchoolRepository schoolRepository, ClassRepository classRepository, StudentRepository studentRepository)
        {
            bool running = true;

            while (running)
            {
                Console.WriteLine("\n班级管理：");
                Console.WriteLine("1. 添加班级");
                Console.WriteLine("2. 查看所有班级");
                Console.WriteLine("3. 查看班级详情");
                Console.WriteLine("4. 更新班级信息");
                Console.WriteLine("5. 删除班级");
                Console.WriteLine("0. 返回上一级");

                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        // 显示所有学校供选择
                        var schools = schoolRepository.GetAll();
                        Console.WriteLine("\n请选择所属学校：");
                        Console.WriteLine("ID\t名称");
                        foreach (var school in schools)
                        {
                            Console.WriteLine($"{school.Id}\t{school.Name}");
                        }

                        Console.WriteLine("请输入学校ID：");
                        if (int.TryParse(Console.ReadLine(), out int classSchoolId))
                        {
                            var selectedSchool = schoolRepository.GetById(classSchoolId);
                            if (selectedSchool != null)
                            {
                                Console.WriteLine("请输入班级名称：");
                                string className = Console.ReadLine();

                                var newClass = new Class
                                {
                                    Name = className,
                                    SchoolId = classSchoolId
                                };

                                int classId = classRepository.Create(newClass);
                                Console.WriteLine($"班级添加成功，ID：{classId}");
                            }
                            else
                            {
                                Console.WriteLine("未找到该学校！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "2":
                        var classes = classRepository.GetAll();
                        Console.WriteLine("\n所有班级：");
                        Console.WriteLine("ID\t名称\t\t所属学校");
                        foreach (var @class in classes)
                        {
                            Console.WriteLine($"{@class.Id}\t{@class.Name}\t\t{@class.School.Name}");
                        }
                        break;

                    case "3":
                        Console.WriteLine("请输入班级ID：");
                        if (int.TryParse(Console.ReadLine(), out int viewClassId))
                        {
                            var @class = classRepository.GetById(viewClassId);
                            if (@class != null)
                            {
                                Console.WriteLine($"\n班级详情：ID={@class.Id}, 名称={@class.Name}, 所属学校={@class.School.Name}, 创建时间={@class.CreatedAt}");

                                var students = studentRepository.GetByClassId(viewClassId);
                                Console.WriteLine("\n该班级的学生：");
                                Console.WriteLine("ID\t姓名\t年龄\t性别");
                                foreach (var student in students)
                                {
                                    Console.WriteLine($"{student.Id}\t{student.Name}\t{student.Age}\t{student.Gender}");
                                }
                            }
                            else
                            {
                                Console.WriteLine("未找到该班级！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "4":
                        Console.WriteLine("请输入要更新的班级ID：");
                        if (int.TryParse(Console.ReadLine(), out int updateClassId))
                        {
                            var classToUpdate = classRepository.GetById(updateClassId);
                            if (classToUpdate != null)
                            {
                                Console.WriteLine($"当前名称：{classToUpdate.Name}，请输入新名称（留空则保持不变）：");
                                string newName = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newName))
                                {
                                    classToUpdate.Name = newName;
                                }

                                // 显示所有学校供选择
                                var allSchools = schoolRepository.GetAll();
                                Console.WriteLine("\n当前所属学校：" + classToUpdate.School.Name);
                                Console.WriteLine("请选择新的所属学校（输入ID，留空则保持不变）：");
                                Console.WriteLine("ID\t名称");
                                foreach (var school in allSchools)
                                {
                                    Console.WriteLine($"{school.Id}\t{school.Name}");
                                }

                                string newSchoolIdInput = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newSchoolIdInput) && int.TryParse(newSchoolIdInput, out int newSchoolId))
                                {
                                    var selectedSchool = schoolRepository.GetById(newSchoolId);
                                    if (selectedSchool != null)
                                    {
                                        classToUpdate.SchoolId = newSchoolId;
                                    }
                                    else
                                    {
                                        Console.WriteLine("未找到该学校，学校ID保持不变！");
                                    }
                                }

                                classRepository.Update(classToUpdate);
                                Console.WriteLine("班级信息更新成功！");
                            }
                            else
                            {
                                Console.WriteLine("未找到该班级！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "5":
                        Console.WriteLine("请输入要删除的班级ID：");
                        if (int.TryParse(Console.ReadLine(), out int deleteClassId))
                        {
                            // 确认删除
                            Console.WriteLine("警告：删除班级将同时删除其所有学生！是否继续？(y/n)");
                            string confirm = Console.ReadLine();
                            if (confirm.ToLower() == "y")
                            {
                                classRepository.Delete(deleteClassId);
                                Console.WriteLine("班级删除成功！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "0":
                        running = false;
                        break;

                    default:
                        Console.WriteLine("无效选择，请重新输入。");
                        break;
                }
            }
        }

        static void ManageStudents(ClassRepository classRepository, StudentRepository studentRepository)
        {
            bool running = true;

            while (running)
            {
                Console.WriteLine("\n学生管理：");
                Console.WriteLine("1. 添加学生");
                Console.WriteLine("2. 查看所有学生");
                Console.WriteLine("3. 查看学生详情");
                Console.WriteLine("4. 更新学生信息");
                Console.WriteLine("5. 删除学生");
                Console.WriteLine("0. 返回上一级");

                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        // 显示所有班级供选择
                        var classes = classRepository.GetAll();
                        Console.WriteLine("\n请选择所属班级：");
                        Console.WriteLine("ID\t名称\t\t所属学校");
                        foreach (var @class in classes)
                        {
                            Console.WriteLine($"{@class.Id}\t{@class.Name}\t\t{@class.School.Name}");
                        }

                        Console.WriteLine("请输入班级ID：");
                        if (int.TryParse(Console.ReadLine(), out int studentClassId))
                        {
                            var selectedClass = classRepository.GetById(studentClassId);
                            if (selectedClass != null)
                            {
                                Console.WriteLine("请输入学生姓名：");
                                string studentName = Console.ReadLine();

                                Console.WriteLine("请输入学生年龄：");
                                if (int.TryParse(Console.ReadLine(), out int studentAge))
                                {
                                    Console.WriteLine("请输入学生性别：");
                                    string studentGender = Console.ReadLine();

                                    var newStudent = new Student
                                    {
                                        Name = studentName,
                                        Age = studentAge,
                                        Gender = studentGender,
                                        ClassId = studentClassId
                                    };

                                    int studentId = studentRepository.Create(newStudent);
                                    Console.WriteLine($"学生添加成功，ID：{studentId}");
                                }
                                else
                                {
                                    Console.WriteLine("无效的年龄！");
                                }
                            }
                            else
                            {
                                Console.WriteLine("未找到该班级！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "2":
                        var students = studentRepository.GetAll();
                        Console.WriteLine("\n所有学生：");
                        Console.WriteLine("ID\t姓名\t年龄\t性别\t班级\t学校");
                        foreach (var student in students)
                        {
                            Console.WriteLine($"{student.Id}\t{student.Name}\t{student.Age}\t{student.Gender}\t{student.Class.Name}\t{student.Class.School.Name}");
                        }
                        break;

                    case "3":
                        Console.WriteLine("请输入学生ID：");
                        if (int.TryParse(Console.ReadLine(), out int viewStudentId))
                        {
                            var student = studentRepository.GetById(viewStudentId);
                            if (student != null)
                            {
                                Console.WriteLine($"\n学生详情：ID={student.Id}, 姓名={student.Name}, 年龄={student.Age}, 性别={student.Gender}, " +
                                    $"班级={student.Class.Name}, 学校={student.Class.School.Name}, 创建时间={student.CreatedAt}");
                            }
                            else
                            {
                                Console.WriteLine("未找到该学生！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "4":
                        Console.WriteLine("请输入要更新的学生ID：");
                        if (int.TryParse(Console.ReadLine(), out int updateStudentId))
                        {
                            var studentToUpdate = studentRepository.GetById(updateStudentId);
                            if (studentToUpdate != null)
                            {
                                Console.WriteLine($"当前姓名：{studentToUpdate.Name}，请输入新姓名（留空则保持不变）：");
                                string newName = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newName))
                                {
                                    studentToUpdate.Name = newName;
                                }

                                Console.WriteLine($"当前年龄：{studentToUpdate.Age}，请输入新年龄（留空则保持不变）：");
                                string newAgeInput = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newAgeInput) && int.TryParse(newAgeInput, out int newAge))
                                {
                                    studentToUpdate.Age = newAge;
                                }

                                Console.WriteLine($"当前性别：{studentToUpdate.Gender}，请输入新性别（留空则保持不变）：");
                                string newGender = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newGender))
                                {
                                    studentToUpdate.Gender = newGender;
                                }

                                // 显示所有班级供选择
                                var allClasses = classRepository.GetAll();
                                Console.WriteLine("\n当前所属班级：" + studentToUpdate.Class.Name);
                                Console.WriteLine("请选择新的所属班级（输入ID，留空则保持不变）：");
                                Console.WriteLine("ID\t名称\t\t所属学校");
                                foreach (var @class in allClasses)
                                {
                                    Console.WriteLine($"{@class.Id}\t{@class.Name}\t\t{@class.School.Name}");
                                }

                                string newClassIdInput = Console.ReadLine();
                                if (!string.IsNullOrEmpty(newClassIdInput) && int.TryParse(newClassIdInput, out int newClassId))
                                {
                                    var selectedClass = classRepository.GetById(newClassId);
                                    if (selectedClass != null)
                                    {
                                        studentToUpdate.ClassId = newClassId;
                                    }
                                    else
                                    {
                                        Console.WriteLine("未找到该班级，班级ID保持不变！");
                                    }
                                }

                                studentRepository.Update(studentToUpdate);
                                Console.WriteLine("学生信息更新成功！");
                            }
                            else
                            {
                                Console.WriteLine("未找到该学生！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "5":
                        Console.WriteLine("请输入要删除的学生ID：");
                        if (int.TryParse(Console.ReadLine(), out int deleteStudentId))
                        {
                            // 确认删除
                            Console.WriteLine("是否确认删除该学生？(y/n)");
                            string confirm = Console.ReadLine();
                            if (confirm.ToLower() == "y")
                            {
                                studentRepository.Delete(deleteStudentId);
                                Console.WriteLine("学生删除成功！");
                            }
                        }
                        else
                        {
                            Console.WriteLine("无效的ID！");
                        }
                        break;

                    case "0":
                        running = false;
                        break;

                    default:
                        Console.WriteLine("无效选择，请重新输入。");
                        break;
                }
            }
        }

        static void ViewLogs(LogRepository logRepository)
        {
            bool running = true;

            while (running)
            {
                Console.WriteLine("\n操作日志：");
                Console.WriteLine("1. 查看所有日志");
                Console.WriteLine("2. 按表名筛选日志");
                Console.WriteLine("0. 返回上一级");

                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        var allLogs = logRepository.GetAll();
                        Console.WriteLine("\n所有操作日志：");
                        Console.WriteLine("ID\t操作时间\t\t\t表名\t\t操作\t\t记录ID\t详情");
                        foreach (var log in allLogs)
                        {
                            Console.WriteLine($"{log.Id}\t{log.CreatedAt}\t{log.TableName}\t\t{log.Action}\t\t{log.RecordId ?? "N/A"}\t{log.Details ?? "N/A"}");
                        }
                        break;

                    case "2":
                        Console.WriteLine("请输入表名（Schools/Classes/Students/Logs）：");
                        string tableName = Console.ReadLine();
                        var filteredLogs = logRepository.GetByTableName(tableName);
                        Console.WriteLine($"\n{tableName}表的操作日志：");
                        Console.WriteLine("ID\t操作时间\t\t\t表名\t\t操作\t\t记录ID\t详情");
                        foreach (var log in filteredLogs)
                        {
                            Console.WriteLine($"{log.Id}\t{log.CreatedAt}\t{log.TableName}\t\t{log.Action}\t\t{log.RecordId ?? "N/A"}\t{log.Details ?? "N/A"}");
                        }
                        break;

                    case "0":
                        running = false;
                        break;

                    default:
                        Console.WriteLine("无效选择，请重新输入。");
                        break;
                }
            }
        }
    }
}